/*
 * @Author: owen 
 * @Date: 2017-12-06 14:51:29 
 * @Last Modified by: owen
 * @Last Modified time: 2017-12-06 16:55:41
 * 用于rsa加密
 */
package models

import (
	"crypto"
	"fmt"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
)

 // 公钥和私钥可以从文件中读取
var privateKey = []byte(`
-----BEGIN RSA PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC6CdGbHAzFPrHr9LGXcH6rAZFD8AYKcmz
Y6dj6xwTdWiN5XzwjnIxoxxnZqzPvQm90Y9d5LIrPnXnYlzAn2XCRWD4oiUyV/LxlVLuCL3+DHdUoEcLY37
St+GCvjtAlk2F3RHaJZb3lHYEjzABP45bRhJR9rE9UPAkEizs5bFP6t9mD3ojhcGNROK3TN1ki9PaaECB9q
LLy5aCnpNJxhaZFIgjqPH69VQjBVwyNBjXReQj7WdWykZT6F8Jhz61p1ACQ7vO4katAPjudfsmihAXX+XWD
tOj2XgsPzK5KFGAFN1S9vZifHTNUjDz50me8JsPpRmX6LY+MEvir077iEs2bAgMBAAECggEAMw8s0xhwvNY
HOQ5wi3LZoQ+OEgpXbhiXnTUZU0K6KBJsOAyWUePOeZdjleUyHNGsC1K3uc8qze6XmYVtNxKrnYiNjsyYE3
ZJMrp9uC5XHeJbNWMiiiljynen+acFo7p+fqBwtCcTZkWhwvRjhYmeRCTSKGfZYfIUO4YHHCyKI/5GZyxIq
ujWEt6H03CMTtU6c+EivOo07QEpw6JlT1G1gWnsYwteYYTytsAHvaUUD52XEnN7ovIx9Izb/4Zh4/5rx1J4
zMyA6GnXFZo2eQryWfS8yooaZcSCHhNJQrb5fu6vKl9liAZnTBaHEwmvx374pOlz65e/g7/UN3qpmvFs+QK
BgQD+T+vcRBUf6NADUXTZ5na/QmIMrCulMNJn/e8Y3D+CwkdqbmrGk5YjPiju9J1SRrKWfvecwx+Qmx2hWf
bCXeGnc6/U1oZ2DAP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s7OWxT+rfZg96I4XBjUTit0zdZIvT2mhAgfaiy8uWgp
6TScYWmRSII6jx+vVUIwVcMjQY10XkI+1nVspGU+hfCYc+tadQAkO7zuJGrQD47nX7JooQF1/l1g7To9l4L
D8yuShRgBTdUvb2Ynx0zVIw8+dJnvCbD6UZl+i2PjBL4q9O+4hLNmwIDAQAB
-----END PUBLICK KEY-----
`)
	
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	// fmt.Println(string(publicKey))
	// block, _ := pem.Decode(publicKey)
	// fmt.Println(string(block.Bytes))
	// if block == nil {
	// 	return nil, errors.New("public key error")
	// }
	// pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	// fmt.Println("22222222222222")
	// if err != nil {
	// 	return nil, err
	// }	
	// pub := pubInterface.(*rsa.PublicKey)
	// fmt.Println("33333333333333")
	// return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)

	fmt.Println(string(privateKey))
	block, _ := pem.Decode(privateKey)
	fmt.Println(string(block.Bytes))
	if block == nil {
		return nil, errors.New("public key error")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	fmt.Println("22222222222222")
	if err != nil {
		return nil, err
	}	
	s,err:=rsa.SignPKCS1v15(nil, priv, crypto.SHA256,origData)
	fmt.Println(string(s))
	return s,err
}
	
// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
